//
//  PayViewController.m
//  WisdomZhuHai
//
//  Created by Admin on 14-10-31.
//  Copyright (c) 2014年 wyd. All rights reserved.
//

#import "PayViewController.h"
#import "SSCheckBoxView.h"

#define PAY_IDENTIFIER @"identifier"
#define PAY_ICON @"icon"
#define PAY_NAME @"name"
#define PAY_SUBTITLE @"subTitle"
#define PAY_IFSELECTED @"ifSelected"

@interface PayViewController () {
    SSCheckBoxView* _open;
}

@property (nonatomic,strong) NSArray* payways;//每一项为一个支付渠道相关的字典：identifier(渠道标识)、icon(图标)、name(渠道名称)、ifSelected(是否被选择)
@property (nonatomic, strong) NSMutableArray* couponList;

@property (nonatomic,strong) NSString* curPaywayIdentifier;

@property (nonatomic, assign)int payCouponIndex;
@property (nonatomic, assign)int balanceIndex;
@property (nonatomic, assign)int payWayIndex;
@property (nonatomic, assign)int confirmIndex;

@property (nonatomic, assign)BOOL isOpen;
@property (nonatomic, strong)NSString* cash;
@property (nonatomic, assign)int isUseBalance;
@property (nonatomic, assign)NSString* sn;
@property (nonatomic, assign)float lastPrice;
@property (nonatomic, assign)float couponPrice;

@end

@implementation PayViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"提交订单";
//    self.payment_mode = @"0";
    if ([_payment_mode isEqualToString:@"0"]) {
        self.payways = @[
                         [NSMutableDictionary dictionaryWithDictionary:@{PAY_IDENTIFIER:PAYWAY_IDENTIFIER_ALIPAY, PAY_ICON:@"pay/icon_alipay", PAY_NAME:@"支付宝", PAY_SUBTITLE:@"推荐有支付宝账号的用户使用", PAY_IFSELECTED:[NSNumber numberWithBool:YES]}],[NSMutableDictionary dictionaryWithDictionary:@{PAY_IDENTIFIER:PAYWAY_IDENTIFIER_UPPAY, PAY_ICON:@"pay/icon_bank", PAY_NAME:@"银联",PAY_SUBTITLE:@"支持储蓄卡信用卡，无需开通网银", PAY_IFSELECTED:[NSNumber numberWithBool:NO]}]];
    } else if ([_payment_mode isEqualToString:@"1"]) {
        self.payways = @[
                         [NSMutableDictionary dictionaryWithDictionary:@{PAY_IDENTIFIER:PAYWAP_IDENTIFIER_NOPAY, PAY_ICON:@"pay/cashPay", PAY_NAME:@"现场支付", PAY_SUBTITLE:@"到达目的地现场支付", PAY_IFSELECTED:[NSNumber numberWithBool:YES]}]];
    }
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [Common colorWithRGB:0xf2f2f2];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.f)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.f)];
    self.tableView.tableFooterView.backgroundColor = self.tableView.backgroundColor;
    [self initIndex];
    [self getCouponList];
    _isOpen = NO;
    self.isUseBalance = 1;
    self.lastPrice = self.totalPrice;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) initIndex {
    if ([_payment_mode isEqualToString:@"0"]) {
        self.payCouponIndex = 1;
        self.balanceIndex = 2;
        self.payWayIndex = 3;
        self.confirmIndex = 4;
    } else if([_payment_mode isEqualToString:@"1"]) {
        self.payCouponIndex = -1;
        self.payWayIndex = 1;
        self.balanceIndex = -1;
        self.confirmIndex = 2;
    } else {
        self.payCouponIndex = -1;
        self.balanceIndex = -2;
        self.payWayIndex = 1;
        self.confirmIndex = 2;
    }
}

- (IBAction)onConfirm:(id)sender
{
    NSLog(@"onConfirm");
    if (self.lastPrice <= 0) {
        [self didPayCompleted:TRUE payStatus:@"0000"];
    }else{
        for (NSDictionary* dic in self.payways) {
            BOOL ifSelected = [dic[PAY_IFSELECTED] boolValue];
            if (ifSelected) {
                self.curPaywayIdentifier = dic[PAY_IDENTIFIER];
                [self confirmOrderPay];
                return;
            }
        }
    }
}

#pragma mark - Protocol request
- (void)getCouponList {
    NSString *orderSn = [Common valueForKey:P_ORDERSN dic:_orderInfo];
    [[ProtocolManager shareInstance] getCouponListForPay:orderSn andTarget:self andSelector:@selector(getCouponListCallback:)];
}

- (void)confirmOrderPay
{
    NSString *orderSN = [Common valueForKey:P_ORDERSN dic:self.orderInfo];
    [[ProtocolManager shareInstance] confirmOrderPay:orderSN payWay:self.curPaywayIdentifier isUseBalance:_isUseBalance coupon:_sn target:self selector:@selector(confirmOrderPayCallback:)];
}

- (void)completeOrder:(NSString*)result paystatus:(NSString *)paystatus
{
    NSString *orderSN = [Common valueForKey:P_ORDERSN dic:self.orderInfo];
    [[ProtocolManager shareInstance] completeOrder:result paystatus:paystatus orderSN:orderSN note:nil target:self selector:@selector(completeOrderCallback:)];
}

#pragma mark - Protocol call back
- (void)getCouponListCallback:(NSDictionary*)dic {
    NSLog(@"%s,%@",__FUNCTION__, dic);
    if (dic == nil) {
        return;
    }
    self.couponList = [NSMutableArray array];
    NSArray *couponList = [Common valueForKey:P_RESULT dic:dic];
    NSString *cash = [Common valueForKey:P_CASH dic:dic];
    self.cash = [NSString stringWithFormat:@"%@", cash];
    if ([couponList isKindOfClass:[NSArray class]]) {
        [self.couponList addObjectsFromArray:couponList];
    }
    [self.tableView reloadData];
}

- (void)confirmOrderPayCallback:(NSDictionary*)dic
{
    NSLog(@"confirmOrderPayCallback %@", dic)
    if (dic == nil) {
        return;
    }
    NSString *respCode = [Common valueForKey:P_RESPCODE dic:dic];
    if ([respCode isEqualToString:CODE_HANDLE_SUCCESS]) {
        if ([_payment_mode isEqualToString:@"0"]){
            NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
            [params setValuesForKeysWithDictionary:self.orderInfo];
            if (_totalPrice == _lastPrice) {
                params[P_ORDERPRICE] = [NSNumber numberWithFloat:self.totalPrice];
            } else {
                params[P_ORDERPRICE] = [NSNumber numberWithFloat:self.lastPrice];
            }
            params[P_NAME] = self.goodsName;
            params[P_INTRO] = [NSString stringWithFormat:@"%@ %@", self.storeName, self.goodsName];
            [[PaymentManager shareInstance] startPay:self.curPaywayIdentifier withParams:params fromViewController:self];
            [PaymentManager shareInstance].delegate = self;
        } else {
            [self didPayCompleted:TRUE payStatus:CODE_HANDLE_SUCCESS];
        }
    }
}

- (void)completeOrderCallback:(NSDictionary*)dic
{
    NSLog(@"completeOrderCallback %@", dic)
    if (dic == nil) {
        return;
    }
    //NSString *respCode = [Common valueForKey:P_RESPCODE dic:dic];
}

#pragma mark - PaymentManagerDelegate
- (void)didPayCanceled:(NSString*)payStatus
{
    [self completeOrder:@"false" paystatus:payStatus];
    [self performSelector:@selector(popPayView) withObject:nil afterDelay:1.2];
}

- (void)didPayCompleted:(BOOL)ifSuccessed payStatus:(NSString*)payStatus
{
    if (ifSuccessed) {
        [self completeOrder:@"success" paystatus:payStatus];
        if ([_payment_mode isEqualToString:@"0"]){
            [[Common shareInstance] showAlertViewWithTitle:@"支付成功!" text:nil dismissTime:1.0];
        } else {
            [[Common shareInstance] showAlertViewWithTitle:@"预约成功!" text:nil dismissTime:1.0];
        }
        [self performSelector:@selector(popPayAndOrderView) withObject:nil afterDelay:1.2];
        [self.PersonOrderDetailDeletage refreshCell];
    }
    else {
        [self completeOrder:@"false" paystatus:payStatus];
        [[Common shareInstance] showAlertViewWithTitle:@"支付失败!" text:nil dismissTime:1.0 dismissed:nil];
        [self performSelector:@selector(popPayView) withObject:nil afterDelay:1.2];
    }
}

#pragma mark - Private
- (void)loadPayInfoCellData:(UITableViewCell*)cell
{
    UIView *view = [cell viewWithTag:1000];
    view.layer.cornerRadius = 3.0;
    view.layer.borderColor = [Common colorWithRGB:0xcccccc].CGColor;
    view.layer.borderWidth = 1;
//    view.layer.shadowOffset = CGSizeMake(1, 1);
//    view.layer.shadowOpacity = 0.2;
//    view.layer.shadowRadius = 1.0;
    UILabel *lbName = (UILabel*)[cell viewWithTag:1001];
    UILabel *lbNum = (UILabel*)[cell viewWithTag:1002];
    UILabel *lbPrice = (UILabel*)[cell viewWithTag:1003];
    lbName.text = [NSString stringWithFormat:@"%@", self.goodsName];
    lbNum.text = [NSString stringWithFormat:@"%d份", self.num];
    lbPrice.text = [NSString stringWithFormat:@"%.2f元", self.totalPrice];
}

- (void)loadPayWayCellData:(UITableViewCell*)cell index:(int)index
{
    if (index >= self.payways.count) {
        return;
    }
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, 0, 300, 60)];
    view.backgroundColor = [UIColor whiteColor];
    view.layer.cornerRadius = 3.0;
    view.layer.borderColor = [Common colorWithRGB:0xcccccc].CGColor;
    view.layer.borderWidth = 1;
//    view.layer.shadowOffset = CGSizeMake(1, 0);
//    view.layer.shadowOpacity = 0.2;
//    view.layer.shadowRadius = 1.0;
    UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake(11, 14, 40, 32)];
    UILabel* lbName = [[UILabel alloc] initWithFrame:CGRectMake(54, 14, 148, 17)];
    lbName.textColor = [Common colorWithRGB:0x555555];
    lbName.font = [UIFont fontWithName:@"Arial" size:14.0];
    UIView* checkView = [[UIView alloc] initWithFrame:CGRectMake(272, 0, 20, 60)];
    UILabel* lbSubTitle = [[UILabel alloc] initWithFrame:CGRectMake(54, 36, 206, 10)];
    lbSubTitle.textColor = [Common colorWithRGB:0xcccccc];
    lbSubTitle.font = [UIFont fontWithName:@"Arial" size:12.0];
    NSDictionary* dic = self.payways[index];
    [imgView setImage:[UIImage imageNamed:dic[PAY_ICON]]];
    lbName.text = dic[PAY_NAME];
    lbSubTitle.text = dic[PAY_SUBTITLE];
    BOOL ifChecked = [dic[PAY_IFSELECTED] boolValue];
    SSCheckBoxView* cb = (SSCheckBoxView*)[cell.contentView viewWithTag:1100];
    if (cb == nil) {
        cb = [[SSCheckBoxView alloc] initWithFrame:CGRectMake(0, 12, 20, 20) style:kSSCheckBoxViewStyleCustom checked:NO];
        [cb setCheckedImage:@"pay/circle_choose" uncheckedImage:@"pay/circle_not_choose"];
        cb.tag = 1100;
        [checkView addSubview:cb];
        cb.userInteractionEnabled = NO;
    }
    [cb setChecked:ifChecked];
    [view addSubview:imgView];
    [view addSubview:lbName];
    [view addSubview:checkView];
    [view addSubview:lbSubTitle];
    [cell.contentView addSubview:view];
}

- (void)loadCouponCellData:(UITableViewCell*)cell index:(int)index
{
    if (index >= self.couponList.count) {
        return;
    }
    NSDictionary *cellData = _couponList[index];
    NSString *sn = [Common valueForKey:P_SN dic:cellData];
    NSString *cash2 = [Common valueForKey:P_CASH2 dic:cellData];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, 0, 300, 40)];
    view.backgroundColor = [UIColor clearColor];
    UILabel* lbName = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 150, 40)];
    lbName.textColor = [Common colorWithRGB:0xcccccc];
    lbName.font = [UIFont fontWithName:@"Arial" size:13.0];
    UILabel* lbChoose = [[UILabel alloc] initWithFrame:CGRectMake(254, 0, 26, 40)];
    lbChoose.textColor = [Common colorWithRGB:0xcccccc];
    lbChoose.font = [UIFont fontWithName:@"Arial" size:11.0];
    UIView* checkView = [[UIView alloc] initWithFrame:CGRectMake(277, 12, 15, 15)];
    UILabel* lbNum = [[UILabel alloc] initWithFrame:CGRectMake(188, 0, 50, 40)];
    lbNum.textColor = [Common colorWithRGB:0xcccccc];
    lbNum.font = [UIFont fontWithName:@"Arial" size:14.0];
//    NSDictionary* dic = self.couponList[index];
//    [imgView setImage:[UIImage imageNamed:dic[PAY_ICON]]];
//    lbName.text = dic[PAY_NAME];
    lbName.text = sn;
    lbChoose.text = @"选择";
    lbNum.text = [NSString stringWithFormat:@"%@元", cash2];
//    BOOL ifChecked = [dic[PAY_IFSELECTED] boolValue];
    BOOL ifChecked = [cellData[PAY_IFSELECTED] boolValue];
    SSCheckBoxView* cb = (SSCheckBoxView*)[cell.contentView viewWithTag:3300];
    if (cb == nil) {
        cb = [[SSCheckBoxView alloc] initWithFrame:CGRectMake(0, -10, 15, 15) style:kSSCheckBoxViewStyleCustom checked:NO];
        [cb setCheckedImage:@"pay/spa_choose" uncheckedImage:@"pay/spa_not_choose"];
        cb.tag = 3300;
        [checkView addSubview:cb];
        cb.userInteractionEnabled = NO;
    }
    [cb setChecked:ifChecked];
    [view addSubview:lbName];
    [view addSubview:lbChoose];
    [view addSubview:checkView];
    [view addSubview:lbNum];
    [cell.contentView addSubview:view];
}

- (void)loadBalanceCellData:(UITableViewCell*)cell
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, 0, 300, 50)];
    view.backgroundColor = [UIColor whiteColor];
    view.layer.cornerRadius = 3.0;
    view.layer.borderColor = [Common colorWithRGB:0xcccccc].CGColor;
    view.layer.borderWidth = 1;
//    view.layer.shadowOffset = CGSizeMake(1, 0);
//    view.layer.shadowOpacity = 0.2;
//    view.layer.shadowRadius = 1.0;
    UILabel *balanceLab = [[UILabel alloc] initWithFrame:CGRectMake(11, 0, 200, 50)];
    balanceLab.textColor = [Common colorWithRGB:0x555555];
    balanceLab.font = [UIFont fontWithName:@"Arial" size:14.0];
    balanceLab.text = [NSString stringWithFormat:@"余     额：%@",self.cash];
    [view addSubview:balanceLab];
    UIView *noView = [[UIView alloc] initWithFrame:CGRectMake(220, 0, 85, 50)];
    UITapGestureRecognizer *chooseBalance = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseBalance:)];
    UILabel *noLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 75, 50)];
    noLab.textColor = [Common colorWithRGB:0x555555];
    noLab.font = [UIFont fontWithName:@"Arial" size:14.0];
    noLab.text = @"使用余额";
    UIImageView *noImg = [[UIImageView alloc] initWithFrame:CGRectMake(65, 20, 10, 10)];
    noImg.tag = 4000;
    noImg.image = [UIImage imageNamed:@"pay/spa_choose"];
    [noView addSubview:noLab];
    [noView addSubview:noImg];
    [noView addGestureRecognizer:chooseBalance];

    [cell.contentView addSubview:view];
    [cell.contentView addSubview:noView];
}

- (void)loadlastPayCellData:(UITableViewCell*)cell
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(10, 0, 300, 50)];
    view.backgroundColor = [UIColor whiteColor];
    view.layer.cornerRadius = 3.0;
    view.layer.borderColor = [Common colorWithRGB:0xcccccc].CGColor;
    view.layer.borderWidth = 1;
    UILabel *balanceLab = [[UILabel alloc] initWithFrame:CGRectMake(11, 0, 200, 50)];
    balanceLab.textColor = [Common colorWithRGB:0x555555];
    balanceLab.font = [UIFont fontWithName:@"Arial" size:14.0];
    balanceLab.text = @"还需支付：";
    [view addSubview:balanceLab];
    UIView *noView = [[UIView alloc] initWithFrame:CGRectMake(240, 0, 85, 50)];
    [self lastPayCost];
    UILabel *noLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 85, 50)];
    noLab.textColor = [Common colorWithRGB:0x555555];
    noLab.font = [UIFont fontWithName:@"Arial" size:14.0];
    noLab.text = [NSString stringWithFormat:@"%.2f元",self.lastPrice];
    [noView addSubview:noLab];
    
    [cell.contentView addSubview:view];
    [cell.contentView addSubview:noView];
}

- (void)lastPayCost {
    float cost = 0;
    float balance = 0;
    for(int i = 0; i < _couponList.count; i++) {
        NSDictionary *dic = _couponList[i];
        if ([dic[PAY_IFSELECTED] boolValue]) {
            self.couponPrice = [dic[P_CASH2] floatValue];
        }
    }
    if (_isUseBalance == 1) {
        balance = [_cash floatValue];
    } else {
        balance = 0;
    }
    cost = _couponPrice + balance;
    self.lastPrice = self.totalPrice - cost;
}

- (void)popPayAndOrderView
{
    [self.navigationController popToViewController:self.navigationController.viewControllers[self.navigationController.viewControllers.count-3] animated:YES];
}

- (void)popPayView
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//     Return the number of sections.
    if (self.couponList <= 0) {
        return 3;
    } else {
        if (_payment_mode == nil) {
            return 3;
        }
        return 5;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == _payWayIndex) {
        return self.payways.count;
    } else if (section == _payCouponIndex) {
        if (_isOpen) {
            return self.couponList.count;
        }
        return 0;
    } else if (section == _balanceIndex) {
        return 2;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return PAY_INFO_CELL_HEIGHT;
    } else if (indexPath.section == _payCouponIndex) {
        return PAY_COUPON_CELL_HEIGHT;
    } else if (indexPath.section == _balanceIndex) {
        return PAY_BALANCE_CELL_HEIGHT;
    } else if (indexPath.section == _payWayIndex) {
        return PAY_WAY_CELL_HEIGHT;
    } else if (indexPath.section == _confirmIndex) {
        return PAY_CONFIRM_CELL_HEIGHT;
    } else {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 10;
    } else if (section == _payCouponIndex) {
        return 90;
    }
    return 0;
    
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* view = [[UIView alloc] init];
    view.backgroundColor = self.tableView.backgroundColor;
    if (section == _payCouponIndex) {
        UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(21, 4, 150, 22)];
        lb.textColor = [Common colorWithRGB:0x555555];
        lb.font = [UIFont systemFontOfSize:14];
        lb.text = @"请选择支付方式：";
        [view addSubview:lb];
        UIView *couponView = [[UIView alloc] initWithFrame:CGRectMake(10, 30, 300, 60)];
        couponView.backgroundColor = [UIColor whiteColor];
        couponView.layer.cornerRadius = 3.0;
        couponView.layer.borderColor = [Common colorWithRGB:0xcccccc].CGColor;
        couponView.layer.borderWidth = 1;
//        couponView.layer.shadowOffset = CGSizeMake(1, 1);
//        couponView.layer.shadowOpacity = 0.2;
//        couponView.layer.shadowRadius = 1.0;
        UILabel *couponLabel = [[UILabel alloc] initWithFrame:CGRectMake(11, 20, 100, 20)];
        couponLabel.font = [UIFont fontWithName:@"Arial" size:14.0];
        couponLabel.text = @"代  金  券：";
        UILabel *useCouponLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 20, 100, 20)];
        useCouponLabel.font = [UIFont fontWithName:@"Arial" size:14.0];
        useCouponLabel.text = @"使用代金券";
        [couponView addSubview:couponLabel];
        [couponView addSubview:useCouponLabel];
        UIView* checkView = [[UIView alloc] initWithFrame:CGRectMake(270, 10, 20, 20)];
        _open = (SSCheckBoxView*)[view viewWithTag:2200];
        if (_open == nil) {
            _open = [[SSCheckBoxView alloc] initWithFrame:checkView.bounds style:kSSCheckBoxViewStyleCustom checked:NO];
            [_open setCheckedImage:@"pay/icon_down" uncheckedImage:@"pay/icon_left"];
            _open.tag = 2200;
            [checkView addSubview:_open];
            _open.userInteractionEnabled = NO;
        }
        UITapGestureRecognizer *onTapOpen = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openCoupenList:)];
        [_open setChecked:_isOpen];
        [couponView addGestureRecognizer:onTapOpen];
        [couponView addSubview:checkView];
        [view addSubview:couponView];
    }
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = nil;
    if (indexPath.section == 0) {
        static NSString *CellIdentifier = @"PayInfoCell";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil)
        {
            cell = [[NSBundle mainBundle] loadNibNamed:@"PayCell"  owner:self options:nil][0];
        }
        [self loadPayInfoCellData:cell];
    } else if (indexPath.section == _payCouponIndex) {
        static NSString *CellIdentifier = @"PayCouponCell";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PayCouponCell"];
        } else {
            while ([cell.contentView.subviews lastObject] != nil) {
                [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];  //删除并进行重新分配
            }
        }
        [self loadCouponCellData:cell index:indexPath.row];
    } else if (indexPath.section == _balanceIndex) {
        static NSString *CellIdentifier = @"BalanceCell";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BalanceCell"];
        } else {
            while ([cell.contentView.subviews lastObject] != nil) {
                [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];  //删除并进行重新分配
            }
        }
        if (indexPath.row == 0) {
            [self loadBalanceCellData:cell];
        } else {
            [self loadlastPayCellData:cell];
        }
    } else if (indexPath.section == _payWayIndex) {
        static NSString *CellIdentifier = @"PayWayCell";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PayWayCell"];
        } else {
            while ([cell.contentView.subviews lastObject] != nil) {
                [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];  //删除并进行重新分配
            }
        }
        [self loadPayWayCellData:cell index:indexPath.row];
    } else if (indexPath.section == _confirmIndex) {
        static NSString *CellIdentifier = @"ConfirmCell";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil)
        {
            cell = [[NSBundle mainBundle] loadNibNamed:@"PayCell"  owner:self options:nil][1];
            
            UIButton *btn = (UIButton*)[cell viewWithTag:1001];
            [btn setImage:[UIImage imageNamed:@"pay/pay_btn"] forState:UIControlStateNormal];
            [btn setImage:[UIImage imageNamed:@"pay/pay_btn_on"] forState:UIControlStateHighlighted];
        }

    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
        // Configure the cell...
        if(cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
        }
    }
    cell.contentView.backgroundColor = self.tableView.backgroundColor;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == _payWayIndex) {
        int index = indexPath.row;
        if (index >= self.payways.count) {
            return;
        }
        NSMutableDictionary *dic = self.payways[index];
        BOOL ifSelected = [dic[PAY_IFSELECTED] boolValue];
        if (!ifSelected) {
            dic[PAY_IFSELECTED] = [NSNumber numberWithBool:YES];
            for (int i=0; i<self.payways.count; i++) {
                if (i != index) {
                    dic = self.payways[i];
                    dic[PAY_IFSELECTED] = [NSNumber numberWithBool:NO];
                }
            }
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:_payWayIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    } else if (indexPath.section == _payCouponIndex) {
        int index = indexPath.row;
        if (index >= self.payways.count) {
            return;
        }
        NSMutableDictionary *dic = self.couponList[index];
        BOOL ifSelected = [dic[PAY_IFSELECTED] boolValue];
        if (!ifSelected) {
            dic[PAY_IFSELECTED] = [NSNumber numberWithBool:YES];
            self.sn = [Common valueForKey:P_SN dic:dic];
            for (int i=0; i<self.couponList.count; i++) {
                if (i != index) {
                    dic = self.couponList[i];
                    dic[PAY_IFSELECTED] = [NSNumber numberWithBool:NO];
                }
            }
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:_payCouponIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:_balanceIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }
}

- (void)chooseBalance:(UITapGestureRecognizer*)tap {
    UIImageView *choose = (UIImageView*)[tap.view viewWithTag:4000];
    if (_isUseBalance == 1) {
        choose.image = [UIImage imageNamed:@"pay/spa_not_choose"];
        self.isUseBalance = 0;
    } else {
        choose.image = [UIImage imageNamed:@"pay/spa_choose"];
        self.isUseBalance = 1;
    }
    
}

- (void)openCoupenList:(UITapGestureRecognizer*)onTap {
    if (!_isOpen) {
        [_open setChecked:YES];
//        [self openCoupen:YES];
        _isOpen = YES;
    } else {
        [_open setChecked:NO];
//        [self openCoupen:NO];
        _isOpen = NO;
    }
    [self.tableView reloadData];
}

- (void)openCoupen:(BOOL)state{
    if (state) {
        self.payCouponIndex = 1;
        self.balanceIndex = 2;
        self.payWayIndex = 3;
        self.confirmIndex = 4;
    } else {
        self.payCouponIndex = -1;
        self.balanceIndex = 1;
        self.payWayIndex = 2;
        self.confirmIndex = 3;
    }
    
}

@end
